import React, { Component } from "react";
import './Duanzi.css';
import axios from 'axios'; //简便方式导入

export default class Duaizi extends Component {
    state = {
        duanzis: []
    }

    render() {
        return (
            <div className="duanzi-container">
                <button onClick={this.getDuanzi}>点击获取段子</button>
                <hr />
                <h2>段子列表</h2>
                <hr />
                <table border="1">
                    <thead>
                        <tr><td>ID</td><td>作者</td><td>内容</td></tr>
                    </thead>
                    <tbody>
                        {
                            this.state.duanzis.map(item => {
                                return <tr key={item.id}><td>{item.id}</td><td>{item.name}</td><td>{item.text}</td></tr>
                            })
                        }
                    </tbody>
                </table>
            </div>
        );
    }

    //声明方法
    getDuanzi = async () => {
        try{
            //发送请求 获取段子
            let response = await axios.get('http://api.xiaohigh.com/duanzi')
            //设置状态
            this.setState({
                duanzis: response.data
            })
        }catch(e){
            alert('请求异常, 稍后再试!!');
        }
    }

    //生命周期钩子
    async componentDidMount(){
        //发送请求
        try{
            //发送请求 获取段子
            let response = await axios.get('http://api.xiaohigh.com/duanzi')
            //设置状态
            this.setState({
                duanzis: response.data
            })
        }catch(e){
            alert('请求异常, 稍后再试!!');
        }
    }
}
